package com.isoft.controller;

import com.isoft.service.DfmeRtneService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/flight/rtne")
public class DfmeRtneController {
    private static final Logger logger = LoggerFactory.getLogger(DfmeRtneController.class);

    @Autowired
    private DfmeRtneService dfmeRtneService;

    @PostMapping(value = "/upload",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> uploadFlightData(@RequestParam("file") MultipartFile file) {
        try {
            logger.info("Received DFME-RTNE file upload: {}", file.getOriginalFilename());

            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("{\"error\":\"File cannot be empty\"}");
            }

            if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                return ResponseEntity.badRequest().body("{\"error\":\"Only XML files are supported\"}");
            }

            String result = dfmeRtneService.parseAndSave(file);
            return ResponseEntity.ok("{\"message\":\"" + result + "\"}");
        }catch (Exception e) {
            String errorMsg = e.getMessage();
            // 简化错误信息长度
            if (errorMsg != null && errorMsg.length() > 200) {
                errorMsg = errorMsg.substring(0, 200) + "...";
            }

            logger.error("DFME-RTNE file upload failed: {}", errorMsg, e);
            return ResponseEntity.internalServerError()
                    .body("{\"error\":\"DFME-RTNE processing failed: " + errorMsg + "\"}");
        }
    }
}